package com.haoshuang.zhouzhoubang.ui.activity


import android.os.Bundle
import android.view.Gravity
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.TextView

import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.SizeUtils
import com.gyf.immersionbar.ktx.immersionBar
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.ActivityInvitingMembersBinding
import com.haoshuang.zhouzhoubang.model.bean.SfBean
import com.haoshuang.zhouzhoubang.ui.adapter.MegerAdapter
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.HelpDescriptionBottomDialog
import com.haoshuang.zhouzhoubang.ui.dialog.HelpDescriptionDialog
import com.haoshuang.zhouzhoubang.ui.page.mine.invite.create.CreateTeamMemberAdapter
import com.haoshuang.zhouzhoubang.ui.page.mine.invite.record.InviteTeamMemberRecordActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.invite.skill.ChoosePassSkillListActivity
import com.haoshuang.zhouzhoubang.ui.vm.InvitingMembersViewModel
import com.lnkj.jialubao.utils.AccountUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupPosition
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.core.setOnItemChildClick
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.startPageForResult
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.vertical
import com.qw.curtain.lib.Curtain
import com.qw.curtain.lib.CurtainFlow
import com.qw.curtain.lib.flow.CurtainFlowInterface
import com.qw.curtain.lib.shape.RoundShape

data class AddPhoneNumberBean(
    var phoneNumber: String = "",
)

/**
 *  邀请门店成员界面
 */
class InvitingMembersActivity :
    BaseVMActivity<InvitingMembersViewModel, ActivityInvitingMembersBinding>() {
    private var skills: List<String> = mutableListOf()
    private var id1s = ""
    private var id2s = ""
    private var id3s = ""
    private var chooseNum = 0
    private val data = arrayListOf(AddPhoneNumberBean())
    private val adapter = CreateTeamMemberAdapter(data, ::minus)

    private val memberData = arrayListOf<SfBean>()
    private val memberAdapter = MegerAdapter(memberData)

    // 搜索的手机号
    private var searchPhone = ""

    override fun initImmersionBar() {
        immersionBar {
            statusBarDarkFont(true)
            statusBarColor(R.color.white)
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        binding.apply {
            appBar.ivBack.clickWithTrigger { finish() }
            tvYqj.clickWithTrigger { startPage<InviteTeamMemberRecordActivity>() }
            appBar.tvTitle.text = "邀请门店成员"

            llChooseSkill.clickWithTrigger {
                startPageForResult<ChoosePassSkillListActivity>("id1s" to id1s, "id2s" to id2s, "id3s" to id3s) { code, data ->
                    if (code == 200 && data != null) {
                        id1s = data.getString("id1s")
                        id2s = data.getString("id2s")
                        id3s = data.getString("id3s")
                        skills = data.getString("skills").split(",").filter { it.isNotEmpty() }
                        chooseNum = data.getIntExtra("chooseNum", 0)
                        if (chooseNum == 0) {
                            tvChooseSkillNum.text = ""
                        } else {
                            tvChooseSkillNum.text = "已选${chooseNum}项"
                        }
                    }
                }
            }

            tvAddMember.clickWithTrigger {
                val item = data.first()
                if (item.phoneNumber == "") {
                    toast("请输入手机号")
                    return@clickWithTrigger
                }
                if (item.phoneNumber.length!=11 || !item.phoneNumber.startsWith("1")){
                    toast("请输入正确手机号")
                    return@clickWithTrigger
                }
                // 添加成员
                data.add(0,AddPhoneNumberBean())
                adapter.notifyDataSetChanged()
            }

            etSearchPhone.setOnEditorActionListener(object : TextView.OnEditorActionListener {
                override fun onEditorAction(
                    v: TextView?,
                    actionId: Int,
                    event: KeyEvent?
                ): Boolean {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        searchPhone = etSearchPhone.text.toString()
                        if (searchPhone.isEmpty()){
                            toast("请输入完手机号, 再添加下一位")
                            return true
                        }
                        if (searchPhone.length != 11 || !searchPhone.startsWith("1")){
                            toast("请输入正确手机号, 再添加下一位")
                            return true
                        }
                        vm.getData2("mobile" to searchPhone)
                    }
                    return false
                }
            })

            rvCreateMember.vertical().adapter = adapter

            rvList2.vertical().adapter = memberAdapter
            memberAdapter.setOnItemChildClick(id = R.id.tvShare){view, position, item ->
                vm.getData("phones" to item?.phone)
            }

            ivHelpCate.clickWithTrigger {
                XPopup.Builder(mActivity)
                    .popupPosition(PopupPosition.Bottom)
                    .animationDuration(0)
                    .borderRadius(SizeUtils.dp2px(10f).toFloat())
                    .hasShadowBg(false)
                    .atView(binding.ivHelpCate)
                    .asCustom(HelpDescriptionBottomDialog(mActivity, "同步类别指的是，给邀请的师傅，选择门店已认证的技能"))
                    .show()
            }

            tvRecommendService.clickWithTrigger{
                XPopup.Builder(mActivity)
                    .popupPosition(PopupPosition.Bottom)
                    .animationDuration(0)
                    .borderRadius(SizeUtils.dp2px(10f).toFloat())
                    .hasShadowBg(false)
                    .atView(binding.tvRecommendService)
                    .asCustom(HelpDescriptionBottomDialog(mActivity, "平台推荐的服务师，根据您门店所认证服务类别,筛选后，符合门店的人员进行推送"))
                    .show()
            }

            tvShare.clickWithTrigger {
                // 验证
                if (chooseNum == 0) {
                    toast("请选择技能")
                    return@clickWithTrigger
                }

                // 验证手机号
                if (data.none { it.phoneNumber.isNotEmpty() }) {
                    toast("请填写至少一个手机号")
                    return@clickWithTrigger
                }
                data.filter { it.phoneNumber.isNotEmpty() }.forEach {
                    if (it.phoneNumber.length != 11 || !it.phoneNumber.startsWith("1")){
                        toast("请输入正确的手机号")
                        return@clickWithTrigger
                    }
                }
                // 预览手机号和选择的技能
                XPopup.Builder(mActivity)
                    .asCustom(ConfirmDialog(
                        context =mActivity,
                        title = "邀请新成员",
                        content = "邀请的手机号: \n${data.filter { it.phoneNumber.isNotEmpty() }.joinToString(",") { it.phoneNumber }}\n需要同步的技能: \n${skills.joinToString()}",
                        cancelStr = "取消",
                        contentGravity = Gravity.START,
                        confirmStr = "确认邀请",
                        isHideCancel = false,
                        isHideAgain = false,
                        onCancel = {},
                        onConfirm = {
                            vm.inviteTeamMember(data.filter { it.phoneNumber.isNotEmpty() }.joinToString(",") { it.phoneNumber }, id1s, id2s, id3s)
                        }))
                    .show()

            }
        }

        if (!AccountUtils.inviteMemberGuide){
            showGuide()
        }
    }

    private fun showGuide(){
        CurtainFlow.Builder()
            .with(1, getStepOneGuide())
            .with(2, getStepTwoGuide())
            .create()
            .start(object : CurtainFlow.CallBack{
                override fun onProcess(currentId: Int, curtainFlow: CurtainFlowInterface?) {
                    when(currentId){
                        1 -> {
                            curtainFlow?.findViewInCurrentCurtain<TextView>(R.id.tvNext)
                                ?.click {
                                    curtainFlow.toCurtainById(2)
                                }
                        }
                        2 -> {
                            curtainFlow?.findViewInCurrentCurtain<TextView>(R.id.tvNext)
                                ?.click {
                                    AccountUtils.inviteMemberGuide = true
                                    curtainFlow.finish()
                                }
                        }
                    }
                }

                override fun onFinish() {

                }
            })
    }

    private fun getStepOneGuide(): Curtain {
        return Curtain(mActivity)
            .with(binding.llChooseSkill)
            .withShape(binding.llChooseSkill, RoundShape(12f))
            .setTopView(R.layout.guide_invite_member1)

    }

    private fun getStepTwoGuide(): Curtain {
        return Curtain(mActivity)
            .withShape(binding.llGuide2, RoundShape(12f))
            .setTopView(R.layout.guide_invite_member2)
    }

    override fun initData() {
        vm.getData2()
    }

    override fun startObserve() {
        vm.getData2.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                memberData.clear()
                memberData.addAll(it!!)
                memberAdapter.notifyDataSetChanged()
            }
        }

        vm.inviteTeamMemberData.observeState(this){
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                startPage<FriendInvitationActivity>()
                data.clear()
                data.add(AddPhoneNumberBean())
                adapter.notifyDataSetChanged()
            }
        }

        vm.getData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                toast("邀请成功等待师傅同意")
                vm.getData2("mobile" to searchPhone)
            }
        }
    }

    private fun minus(position: Int) {
        data.removeAt(position)
        adapter.notifyDataSetChanged()
    }

}